﻿<%@ WebHandler Language="C#" Class="captcha" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Web.Script.Serialization;


using Newtonsoft.Json;
using VISS.Web.Frontend;
using NCT.Framework;
using VISS.API.Users;
using VISS.MailImpl;


public class captcha : IHttpHandler, IRequiresSessionState
{
    string resp = string.Empty;
    string result = "";
    IUser _iUser = StructureMapFactory.GetInstance<IUser>();
    IUserPassCode _iUserPassCode = StructureMapFactory.GetInstance<IUserPassCode>();
    IUserGeneralProfile iUserGeneralProfile = StructureMapFactory.GetInstance<IUserGeneralProfile>();
   
    public void ProcessRequest(HttpContext context)
    {
        string type = "";

        if (context.Request.Form["type"] != null)
        {
            type = context.Request.Form["type"].ToString();

            switch (type)
            {
                case "sendpass":
                    SendPassWord(context);
                    break;
                case "changepass":
                    ChangePassWord(context);
                    break;
            }
        }
        else
        {
            GenCaptcha(context);
        }
    }
    
    private void SendMailForgotPassword(UserEnt userEnt, UserGeneralProfileEnt userGenProfileEnt,string HyperLink)
    {
        MailEnt.ForgotPassword ent = new MailEnt.ForgotPassword();
        ent.Subject = "VISS - Thư gửi mật khẩu đăng nhập";
        ent.Email = userEnt.Email;
        ent.FullName = userGenProfileEnt.Name;
        ent.HyperLink = HyperLink;
        ent.UserKey = userEnt.UserKey;
        MailEnt.MailInfo mailInfo = new MailEnt.MailInfo();
        mailInfo.MailContent = SerializerUtils.JsonSerialize(ent);
        mailInfo.SendMailType = ESendMailType.ForgotPassword;

        try
        {
            if (NCT.Mail.MailQueuePD.CreateInstance().AddToQueue(AppSettings.MailType, SerializerUtils.JsonSerialize(mailInfo)) <= 0)
            {
                LogUtils.Error("Sent mail:frontend.viss.vn: active user fail.");
            }
        }
        catch (Exception ex)
        {
            LogUtils.Error("Sent mail fail: " + ex.ToString());
        }
    }


    public void ChangePassWord(HttpContext context)
    {
        string result = "{{\"data\":\"{0}\"}}";
        var passCode = string.Empty;
        var newPassword = string.Empty;
        var confirmNewPassword = string.Empty;
        var expireDate = DateTime.MaxValue;
        var nowDate = DateTime.Now;
        passCode = context.Request.Form["UserKey"].ToString();
        newPassword = context.Request.Form["NewPassWord"].ToString();
        confirmNewPassword = context.Request.Form["ConfirmNewPassword"];
        var userKey = ConvertUtils.HexDecrypt(passCode, "forgotpassword");
        IUser _objectUser = StructureMapFactory.GetInstance<IUser>();
        UserEnt userEnt = null;
        userEnt = _objectUser.GetByUserKey(userKey);

        UserPassCode userInfo = new UserPassCode();

        userInfo = _iUserPassCode.GetByUserKey(userKey);

        if (newPassword.Length < 6 || newPassword.Length > 32)
        {
            FormValidateUtils.Return(string.Format(result, "4"));
            return;
        }

        if (newPassword != confirmNewPassword)
        {
            FormValidateUtils.Return(string.Format(result, "5"));
            return;
        }
        
        if (userInfo == null)
        {
            FormValidateUtils.Return(string.Format(result, "6"));
            return;
        }
        else
        {
            expireDate = userInfo.ExpiredDate;

            int totalDays = expireDate.Subtract(DateTime.Now).Days + 1;

            if(string.Equals(DateTime.Now.ToShortDateString(),expireDate.ToShortDateString()))
            {
                totalDays = 0;
            }
            
            if ((totalDays >= 1) && (totalDays <= 6))
            {
                if (!_objectUser.UpdatePassword(userKey, newPassword))
                {
                    FormValidateUtils.Return(string.Format(result, "0"));
                    return;
                }
                
                userInfo.ExpiredDate = DateTime.Now;

                if (!_iUserPassCode.UpdateExpiredDate(userInfo))
                {
                    FormValidateUtils.Return(string.Format(result, "0"));
                    return;
                }

                FormValidateUtils.Return(string.Format(result, "1"));

            }

            else
            {
                FormValidateUtils.Return(string.Format(result, "7"));
            }

        }
       
    }


    public int WorkingDays(DateTime startDate, DateTime endDate)
    {
        int totalDays = endDate.Subtract(startDate).Days + 1;

        List<DayOfWeek> businessDays = new List<DayOfWeek>() 
                                    { System.DayOfWeek.Monday, System.DayOfWeek.Tuesday, System.DayOfWeek.Wednesday, 
                                        System.DayOfWeek.Thursday, System.DayOfWeek.Friday, System.DayOfWeek.Saturday, System.DayOfWeek.Sunday };

        return Enumerable.Range(0, totalDays)
                .Select(d => startDate.AddDays(d))
                .Where(wd => businessDays.Contains(wd.DayOfWeek)).Count();

    }

    public  void SendPassWord(HttpContext context)
    {
        var email = string.Empty;
        var captcha = string.Empty;
        var genText = string.Empty;
        var hyperLink = string.Empty;
        var userKey = string.Empty;
        var date = string.Empty;
        
        email = context.Request.Form["email"].ToString();
        captcha = context.Request.Form["captcha"].ToString();

        if (context.Session[AppSettings.SESSION_ANTISPAMTEXT] != null)
        {
            genText = context.Session[AppSettings.SESSION_ANTISPAMTEXT].ToString();
        }
        
        if (!string.Equals(captcha, genText))
        {
            result = "captcha";
        }
        else
        {
            UserEnt user = new UserEnt();
   
            ECheckEmailResult rs = _iUser.CheckEmailExisted(email);

            if (rs == ECheckEmailResult.Exist)
            {
                user = _iUser.GetUserByEmail(email);

                UserGeneralProfileEnt userGeneralProfile = new UserGeneralProfileEnt();

                if (user != null)
                {
                    userKey = user.UserKey;
                    date = DateTime.Now.ToString();
                    userGeneralProfile = iUserGeneralProfile.GetByUserKey(user.UserKey);
                }

                string encode = string.Empty;
               
                encode = ConvertUtils.HexEncrypt(userKey, "forgotpassword");

                string decode = ConvertUtils.HexDecrypt(encode, "forgotpassword");

                UserPassCode userPass = new UserPassCode();

                userPass.UserKey = userKey;
                userPass.Code = encode;
                userPass.ExpiredDate = DateTime.Now.AddDays(7);

                if (!_iUserPassCode.Insert(userPass))
                {
                    result = "failed";
                }
                else
                {
                    hyperLink = AppSettings.RootURL + "changepassword?uid=" + encode;

                    //SendMailForgotPassword(user, userGeneralProfile, hyperLink);

                    result = "success";
                }

            }
            else
            {
                result = "emailnotexist";
            }        
        }

        Hashtable htbl = new Hashtable();

        htbl.Add("status", (result == "captcha" ? "captcha" : (result == "emailnotexist" ? "emailnotexist" :(result == "failed" ? "failed":"success"))));

        JavaScriptSerializer js = new JavaScriptSerializer();

        resp = js.Serialize(htbl);

        context.Response.Clear();

        context.Response.Write(resp);

        context.Response.End();
    }
    
    public static void GenCaptcha(HttpContext context)
    {

        int fontSize = 14;
        int bgWidth = 65;
        int bgHeight = 24;

        float x = 1;
        float y = 1;

        string genText = GetUniqueString(4);
        context.Session[AppSettings.SESSION_ANTISPAMTEXT] = genText;

        Bitmap raster;

        Graphics graphicObj;
        string bgFilePath = context.Server.MapPath("~/res/images/capcha/bg-" + new Random().Next(5) + ".jpg");
        System.Drawing.Image imgObj = System.Drawing.Image.FromFile(bgFilePath);

        raster = new Bitmap(imgObj, bgWidth, bgHeight);
        graphicObj = Graphics.FromImage(raster);

        String[] crypticFonts = new String[10];
        crypticFonts[0] = "Arial";
        crypticFonts[1] = "Verdana";
        crypticFonts[2] = "Comic Sans MS";
        crypticFonts[3] = "Impact";
        crypticFonts[4] = "Haettenschweiler";
        crypticFonts[5] = "Lucida Sans Unicode";
        crypticFonts[6] = "Garamond";
        crypticFonts[7] = "Courier New";
        crypticFonts[8] = "Book Antiqua";
        crypticFonts[9] = "Arial Narrow";

        SolidBrush[] brushes = new SolidBrush[1];
        brushes[0] = new SolidBrush(Color.Black);

        for (int a = 0; a < genText.Length; a++)
        {
            Font fontObj = new Font(crypticFonts[new Random().Next(a)], fontSize);

            graphicObj.DrawString(genText.Substring(a, 1), fontObj, brushes[0], x + (a * fontSize), y);
        }

        graphicObj.Flush();

        context.Response.ContentType = "image/gif";

        raster.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);


    }
    public static Random randomGetUniqueString = new Random();


    public static string GetUniqueString(int number)
    {
        string chars = "ABCDEFGHJKLMNPQRSTUVWXYZ123456789";

        string returnString = "";
        for (int i = 0; i < number; i++)
            returnString += chars[randomGetUniqueString.Next(chars.Length)];

        return returnString;
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}